﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ESSManageService.Serilog;
using ESSManageService.Common.Helper;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Debugging;
using Serilog.Events;
using Serilog.Extensions.Hosting;
using Serilog.Sinks.SystemConsole.Themes;

namespace ESSManageService.Extensions
{
    public static class SerilogSetup
    {
        public static IHostBuilder AddSerilogSetup(this IHostBuilder host)
        {
            if (host == null) throw new ArgumentNullException(nameof(host));

            var appPath = AppContext.BaseDirectory;

            var ConsoleLogLevel = LogContextStatic.GetLogLevel(AppSettings.app(new string[] { "Serilog", "MinimumLevel", "ConsoleLogLevel" }).ObjToString());
            var FileLogLevel = LogContextStatic.GetLogLevel(AppSettings.app(new string[] { "Serilog", "MinimumLevel", "FileLogLevel" }).ObjToString());

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.Console(ConsoleLogLevel, theme: SystemConsoleTheme.Colored)
                .WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(evt => evt.Level >= FileLogLevel)
                                    .Filter.ByExcluding(evt => evt.Properties.ContainsKey("Sql"))
                                    .WriteTo.File(Path.Combine(appPath, "logs/APILog-.txt"), rollingInterval: RollingInterval.Day,
                                    fileSizeLimitBytes: 100 * 1024 * 1024, 
                                    retainedFileCountLimit: 1000,
                                    rollOnFileSizeLimit: true,
                                    outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message}{NewLine}{Exception}"
                                    ))
                .WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(e => e.Properties.ContainsKey("Sql"))
                                    .WriteTo.File(Path.Combine(appPath, "logs/SqlLog-.txt"), rollingInterval: RollingInterval.Day,
                                    fileSizeLimitBytes: 100 * 1024 * 1024,
                                    retainedFileCountLimit: 1000,
                                    rollOnFileSizeLimit: true,
                                    outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Message}{NewLine}{Exception}"
                )).CreateLogger();

            host.UseSerilog();
            return host;
        }
    }
}
